<template>
  <div class="progress-box">
    <el-card
      class="login-box"
      :header="activeKey === '1' ? '欢迎注册' : '欢迎登录'"
      :bodyStyle="{ width: '400px', height: '400px' }"
    >
      <el-tabs v-model="activeKey" class="demo-tabs">
        <el-tab-pane label="注册" name="1">
          <el-form
            ref="signFrom"
            :model="register"
            :rules="signRules"
            :validate-on-rule-change="false"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
          >
            <el-form-item name="userAccount" prop="userAccount">
              <el-input
                placeholder="请输入用户名"
                v-model="register.userAccount"
              />
            </el-form-item>

            <el-form-item name="userPsd" prop="userPsd">
              <el-input
                placeholder="密码"
                show-password
                v-model="register.userPsd"
              />
            </el-form-item>

            <el-form-item name="reUserPsd" prop="reUserPsd">
              <el-input
                placeholder="请再次确认密码"
                show-password
                v-model="register.reUserPsd"
              />
            </el-form-item>

            <el-form-item name="userEmail" prop="userEmail">
              <el-input placeholder="绑定邮箱" v-model="register.userEmail" />
            </el-form-item>

            <el-form-item
              class="authCode-item"
              name="emailAuthCode"
              prop="emailAuthCode"
            >
              <el-input
                style="width: 200px"
                placeholder="请输入验证码"
                v-model="register.emailAuthCode"
              />
              <el-button v-show="time === 61" type="primary" @click="timed()"
                >获取验证码</el-button
              >
              <el-button v-show="time !== 61" type="primary" :disabled="true"
                >{{ time }}s后重新获取验证码</el-button
              >
            </el-form-item>

            <el-form-item :wrapper-col="{ offset: 10, span: 16 }">
              <el-button
                type="primary"
                style="width: 100%; height: 40px"
                @click="onFinishSign(signFrom)"
                >注册账号</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="登录" name="2">
          <el-form
            :model="login"
            ref="loginFrom"
            :rules="loginRules"
            :validate-on-rule-change="false"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 16 }"
          >
            <el-form-item name="userAccount" prop="userAccount">
              <el-input
                placeholder="请输入用户名"
                v-model="login.userAccount"
                @blur="unfocus"
              >
              </el-input>
            </el-form-item>

            <el-form-item name="userPsd" prop="userPsd">
              <el-input
                placeholder="密码"
                show-password
                v-model="login.userPsd"
              />
            </el-form-item>

            <el-form-item
              class="authCode-item"
              name="authCode"
              prop="loginAuthCode"
            >
              <el-input
                style="width: 200"
                placeholder="请输入验证码"
                v-model="login.loginAuthCode"
                @keydown.enter="onFinishLogin(loginFrom)"
              />
              <canvas
                id="myCanvas"
                width="80"
                height="30"
                style="border: 1px solid #d3d3d3"
                @click="authCodeFn()"
              ></canvas>
            </el-form-item>

            <!-- <el-form-item name="remember" :wrapper-col="{ offset: 10, span: 16 }">
            <el-checkbox v-model:checked="login.remember">Remember me</el-checkbox>
            <el-button :link="true" type="primary" @click="changeTabs('1')">去注册账号</el-button>
          </el-form-item> -->

            <el-form-item :wrapper-col="{ offset: 10, span: 16 }">
              <el-button
                type="primary"
                style="width: 100%; height: 40px"
                @click="onFinishLogin(loginFrom)"
                >登录</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      v-model="selectMain"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      :align-center="true"
      title="选择您需要进入的界面"
    >
      <el-button @click="selectMainFn('1')">进入首页</el-button>
      <el-button @click="selectMainFn('2')">后台管理</el-button>
      <el-button @click="selectMainFn('')">进度管理</el-button>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, onMounted, computed, ref } from "vue";
import router from "@/router/index";
import { encrypt, decrypt } from "@/uilts/uilts-key";
import { loginRuleFun, signRuleFun } from "./modules/rules";
import type { Register, Login } from "./modules/type";
import { clearProperty } from "@/uilts/uilts-core";
import * as api from "@/api/index";
import { ElMessage as message, ElNotification as NOT } from "element-plus";

// 秘钥
let encryptPas = ref<string>("");
// 后端返回验证码
let authCode = ref<string>("");

// 邮箱验证码
let loginFrom = ref<any>(null);
// 邮箱验证码
let signFrom = ref<any>(null);
// 功能选择控制
let selectMain = ref<boolean>(false);

let time = ref<number>(61);

// 默认展示登录入口
let activeKey = ref<string>("2");

// 注册的数据
let register = reactive<Register>({
  userAccount: "",
  userPsd: "",
  reUserPsd: "",
  userEmail: "",
  emailAuthCode: "",
});
// 登录的数据
let login = reactive<Login>({
  userAccount: "",
  userPsd: "",
  loginAuthCode: "",
});

onMounted(() => {
  api.User.keyCode().then((res: BaseResponse<string>) => {
    if (res.header.code === 999) {
      encryptPas.value = res.body || "";
      authCodeFn();
    }
  });
});

// 注册表单检验规则
const signRules = computed(() => {
  return signRuleFun({
    userPsd: register.userPsd,
    reUserPsd: register.reUserPsd,
    emailAuthCode: emailAuthCode.value,
    signFromRef: signFrom.value,
  });
});

// 登陆表单检验规则
const loginRules = computed(() => {
  return loginRuleFun({ authCode: authCode.value });
});

// 用户名失焦 重新获取验证码
const unfocus = () => {
  authCodeFn();
};

const selectMainFn = (str: string) => {
  if (str === "1") {
    // 进入首页
    message.warning("功能开发中、敬请期待！");
    // router.push({
    //   name: 'homePage'
    // })
  } else if (str === "2") {
    // 进入后台管理
    router.push({
      path: "/note/admin-homePage",
    });
  } else if (str === "3") {
    // 进入进度管理
  } else {
    message.warning("功能开发中、敬请期待！");
  }
  selectMain.value = false;
};

// 邮箱验证码
let emailAuthCode = ref("");
let times: any = ref(null);
const timed = () => {
  if (register.userEmail) {
    api.User.emailAuthCode({ userEmail: register.userEmail }).then(
      (res: BaseResponse<string>) => {
        if (res.header.code === 999 && res.body) {
          message.success("验证码发送成功");
          emailAuthCode.value = res.body;
          // 开启倒计时
          time.value = 60;
          times.value = setInterval(() => {
            time.value--;
            if (time.value == 0) {
              clearInterval(times.value);
              time.value = 61;
            }
          }, 1000);
        }
      }
    );
  } else {
    message.error("请输入邮箱");
  }
};

// 改变tabs
const changeTabs = (num: string) => {
  activeKey.value = num;
};

// 获取验证码函数
const authCodeFn = () => {
  api.User.authCode().then((res: BaseResponse<string>) => {
    if (res.header.code === 999) {
      authCode.value = decrypt(res.body, encryptPas.value);
      createCode(authCode.value || "");
    }
  });
};
// 生成验证码图片
const createCode = (code: string) => {
  var canvas = document.getElementById("myCanvas") as any; //获取画布
  if (canvas) {
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "#FFFFFF";
    ctx.fillRect(0, 0, 80, 30);
    ctx.font = "20px arial";
    // 创建渐变
    var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
    gradient.addColorStop("0", "magenta");
    gradient.addColorStop("0.5", "blue");
    gradient.addColorStop("1.0", "red");
    // 用渐变填色
    ctx.strokeStyle = gradient;
    ctx.strokeText(code, 10, 22); //画布上添加验证码
  }
};

// 注册函数
const onFinishSign = (signFromRef: any) => {
  if (signFromRef) {
    signFromRef.validate((result: boolean) => {
      if (result) {
        let registerFrom = { ...register };
        registerFrom.userPsd = encrypt(registerFrom.userPsd, encryptPas.value);
        delete registerFrom.reUserPsd;
        api.User.register(registerFrom).then((res: BaseResponse<boolean>) => {
          if (res.header.code === 999) {
            /**
             * 注册成功时
             * 1. 跳到登陆界面
             * 2. 清空注册时填写的数据
             * 3. 清除定时器、回归初始状态
             */
            NOT({
              title: "系统消息",
              type: "success",
              message:
                res.header.message || "注册成功、恭喜您成为NOTE的一份子!",
            });
            activeKey.value = "2";
            register = clearProperty(register);
            clearInterval(times.value);
            time.value = 61;
          }
        });
      }
    });
  }
};

// 登录函数
const onFinishLogin = (loginFromRef: any) => {
  if (loginFromRef) {
    loginFromRef.validate((result: boolean) => {
      if (result) {
        let loginData = { ...login };
        loginData.userPsd = encrypt(loginData.userPsd, encryptPas.value);
        api.User.login(loginData).then((res: BaseResponse<objectType<any>>) => {
          if (res.header.code === 999) {
            NOT({
              title: "系统消息",
              type: "success",
              message: res.header.message || "登陆成功",
            });
            selectMain.value = true;
          }
        });
      }
    });
  } else {
    return "";
  }
};
</script>

<style lang="less" scoped>
@backGroundColor: #fff;
@fontColor: #000;
@borderColor: white;
@bkopacaty: rgba(255, 255, 255, 0.3);
:deep(.el-card) {
  border-radius: 8px;
  overflow: hidden;
  background-color: @bkopacaty;
  .el-card-head {
    padding: 0;
    background-color: @bkopacaty;
    .el-card-head-title {
      // background-color: @backGroundColor;
      // background-color: @bkopacaty;
      color: @fontColor;
      text-align: center;
      font-size: 26px;
      border: 1px solid @borderColor;
    }
  }
  .el-card-body {
    background-color: @bkopacaty;
    // background-color: @backGroundColor;
    color: @fontColor;
    font-size: 26px;
  }
}
.progress-box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: linear-gradient(to top, skyblue 20%, #f9f9f9 80%);
  // background: url("../../assets/login-info.jpg") 100% 100%;
}
:deep(.ant-col) {
  max-width: 100% !important;
}
:deep(.el-form-item__content) {
  margin-bottom: 8px;
}
:deep(.el-input__wrapper) {
  background-color: transparent;
}
:deep(.authCode-item) {
  display: flex;
  .el-form-item__content {
    flex-wrap: nowrap;
  }
}
</style>
